<template>
  <div class="course-section">
    <!-- 头部结构 -->
    <div>
      <el-page-header @back="goBack">
      </el-page-header>
      <span>{{ this.courseName }}</span>
      <el-button
      @click="handleAdd"
      style="float:right;margin-top:-25px"
      type="primary">
      ＋添加阶段</el-button>
      <div style="height:30px"></div>
    </div>
    <!-- 树形列表主体结构 -->
    <el-card>
    <el-tree v-loading="isLoading"
      :data="sections" :props="defaultProps"
      draggable
      :allow-drop="handleAllowDrop"
      :expand-on-click-node="false"
      @node-drop="handleNodeDrop">
      <!-- 使用 scoped slot 传入两个参数node和data，分别表示当前节点的 Node 对象和当前节点的数据。 -->
      <div class="inner" slot-scope="{ node, data }">
        <!-- 内容设置 -->
        <span>{{ node.label }}</span>
        <!-- 章节的按钮结构 -->
        <span v-if="data.sectionName" class="actions" style="margin-left: auto">
          <el-button
            size="mini"
            @click="handleEdit(node)">
            编辑
          </el-button>
          <el-button
            size="mini"
            type="primary">
            添加课时
          </el-button>
          <el-button
            size="mini"
            @click="handleStatus(node)">{{ isStatus ? label : '请选择' }}
          </el-button>
        </span>
        <!-- 课时的按钮结构 -->
        <span v-else class="actions">
          <el-button
            size="mini">
            编辑
          </el-button>
           <!-- lessonName: data.theme
          this.$route.query.lessonName -->
          <el-button
            size="mini"
            type="success"
            @click="$router.push({
                name:'course-video',
                params: {
                  courseId
                },
                query: {
                  lessonId: data.id,
                }
              })">
            上传视频
          </el-button>
          <el-button>
            状态
          </el-button>
        </span>
      </div>
    </el-tree>
    <!-- 弹出对话框组件 -->
    <el-dialog :title="isEdit ? '编辑章节' : '添加阶段'"
        :visible.sync="dialogVisible"
        width="50%">
        <section-create-or-edit
        @addSuccess="handleSuccess"
        @cancelSuccess="handleCancel"
        :courseName="this.courseName"
        :scetion-id="sectionId"
        :is-edit="isEdit"
        ></section-create-or-edit>
    </el-dialog>
    <!-- 弹出对话框组件2 -->
    <el-dialog title="提示" :visible.sync="dialogFormVisible"
      width="35%">
      <status-change :status="status" :section-name="sectionName"
       @cancelStatus="handleFail" @changeStatus="handleFinished"></status-change>
    </el-dialog>
   </el-card>
  </div>
</template>

<script>
// 引入接口
import StatusChange from './components/status'
import SectionCreateOrEdit from './components/sectioncreateoredit'
import { getSectionAndLesson, saveOrUpdateSection, saveOrUpdateLesson } from '@/services/section'
// import CourseCreateOrEdit from './components/course-createoredit'
export default {
  name: 'CourseSection',
  components: {
    SectionCreateOrEdit,
    StatusChange
  },
  props: {
    courseId: {
      type: [Number, String],
      required: true
    },
    courseName: {
      type: String
    }
  },
  data () {
    return {
      sections: [],
      defaultProps: {
        children: 'lessonDTOS',
        label (name) {
          return name.sectionName || name.theme
        }
      },
      isLoading: false,
      // 控制对话框的展示
      dialogVisible: false,
      // 判断是编辑还是添加
      isEdit: false,
      // 存储当前要编辑的章节的id
      sectionId: '',
      // 控制对话框2的展示
      dialogFormVisible: false,
      // 保存当前节点的状态
      status: '',
      // 保存当前节点的名字
      sectionName: '',
      // 存储子组件传来的状态
      label: '',
      // 是否在修改状态
      isStatus: false
    }
  },
  created () {
    this.loadSection()
  },
  methods: {
    // 加载章节和课时
    async loadSection () {
      const { data } = await getSectionAndLesson(this.courseId)
      console.log(data)
      this.sections = data.data
    },
    // 节点拖拽能否放置做检测的处理函数
    handleAllowDrop (draggingNode, dropNode, type) {
      // 规则一:只能同级移动 type不能为 inner
      // 规则二:课时只能在当前章节内移动
      return type !== 'inner' && draggingNode.data.sectionId === dropNode.data.sectionId
      // console.log(draggingNode, dropNode)
    },
    // 节点拖拽完成后处理函数
    async handleNodeDrop (draggingNode, dropNode, type, event) {
      this.isLoading = true
      // 有很多章节和课时，需要给每个章节和课时进行最新的排序顺序的请求
      // console.log(dropNode)
      // 用dropNode.parent.childNodes可以取到所有要更新的节点这是一个数组
      // map原理： map作用是映射调用此方法的数组，不会改变原始数组，返回原始数组每一项的操作，组成一个新数组，长度和原始数组一致
      try {
        await Promise.all(dropNode.parent.childNodes.map((item, index) => {
          // 判断是章节还是课时进行的拖拽  再给对应的接口发送请求
          // 如果有section就说明此时拖动的是课时
          if (draggingNode.data.sectionId) {
            // 此时是进行到的是课时的拖拽
            return saveOrUpdateLesson({
              id: item.data.id,
              orderNum: index
            })
          } else {
          // 此时是章节的拖拽
            return saveOrUpdateSection({
              // 获取到了  课时  的id
              id: item.data.id,
              // 排序字段是这个数组的index
              orderNum: index
            })
          }
        }))
        this.$message.success('数据更新成功')
      } catch (error) {
        this.$message.error('数据更新失败', error)
      }
      this.isLoading = false
    },
    goBack () {
      this.$router.push({
        name: 'course'
      })
    },
    // 点击添加角色
    handleAdd () {
      this.dialogVisible = true
      this.isEdit = false
    },
    handleEdit (section) {
      this.dialogVisible = true
      this.isEdit = true
      // this.sectionName = section.label
      // this.sections.forEach((item, index) => {
      //   if (item.sectionName === this.sectionName) {
      //     this.sectionId = item.id
      //     console.log(this.sectionId)
      //   }
      // })
      this.sectionId = section.data.id
      console.log(this.sectionId)
    },
    handleSuccess () {
      this.dialogVisible = false
      this.loadSection()
    },
    handleCancel () {
      this.dialogVisible = false
    },
    handleStatus (data) {
      this.isStatus = true
      console.log(data)
      this.dialogFormVisible = true
      this.status = data.data.status
      this.sectionName = data.data.sectionName
      // console.log(this.status)
    },
    handleFail () {
      this.dialogFormVisible = false
    },
    handleFinished (num, numl) {
      this.dialogFormVisible = false
      console.log(num)
      console.log(numl)
      num.forEach(item => {
        console.log(item.label)
        console.log(item.value)
        if (numl === item.value) {
          this.label = item.label
          console.log(this.label)
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.inner {
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  border-bottom: 1px solid #eee;
}
::v-deep .el-tree-node__content {
  height: auto
}
</style>
